package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;
import dao.IRainQualityDao;
import entity.RainQuality;
import service.IRainQualityService;

public class RainQualityDaoImpl extends BaseDao implements IRainQualityDao {
    @Override
    public List<RainQuality> findAll() throws SQLException {
        System.out.println("RainQualityDaoImpl.findAll()");
        // 数据库查询逻辑
        List<RainQuality> rainQualities = new ArrayList<>();
        String sql = "SELECT * FROM rainQuality ORDER BY monitorTime DESC";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                RainQuality rainQuality = new RainQuality();
                rainQuality.setId(rs.getInt("id"));
                rainQuality.setDistrictName(rs.getString("districtName"));
                rainQuality.setMonitorTime(rs.getString("monitorTime"));
                rainQuality.setRain(rs.getInt("rain"));
                rainQuality.setMonitoringStation(rs.getString("monitoringStation"));
                rainQuality.setMonitoringAddress(rs.getString("monitoringAddress"));

                rainQualities.add(rainQuality);
            }
        }

        return rainQualities;
    }

    @Override
    public int add(RainQuality rainQuality) throws SQLException {
        String sql = "INSERT INTO rainQuality (districtName, monitorTime, rain, monitoringStation, monitoringAddress) VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, rainQuality.getDistrictName());
            pstmt.setString(2, rainQuality.getMonitorTime());
            pstmt.setInt(3, rainQuality.getRain());
            pstmt.setString(4, rainQuality.getMonitoringStation());
            pstmt.setString(5, rainQuality.getMonitoringAddress());

            return pstmt.executeUpdate();
        }
    }

    @Override
    public int deleteById(int id) throws SQLException {
        String sql = "DELETE FROM rainQuality WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);

            return pstmt.executeUpdate();
        }
    }
}
